package com.chance.cc.crawler.development.scripts.bendibao;

import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.selector.Selectable;
import com.chance.cc.crawler.core.tags.crawler.CrawlerResultTags;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.article;
import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.interaction;

public class BenDiBaoCrawlerScript extends CrawlerCommonScript {
    private Logger log= LoggerFactory.getLogger(BenDiBaoCrawlerScript.class);
    private static boolean bool=true;
    @Override
    public String domain() {
        return "bendibao";
    }

    @Override
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        return true;
    }

    @Override
    public void initUrlRegulars() {
        addUrlRegular("http://sh\\.bendibao\\.com/news/list_17_162_1\\.htm");
        addUrlRegular("http://sh\\.bendibao\\.com/news/list_17_\\d*_\\d*\\.htm");
        addUrlRegular("http://sh\\.bendibao\\.com/\\S*/\\d*/\\d*\\.shtm");
    }

    @Override
    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks=new ArrayList<>();
        String lastUrl = httpPage.getRequest().getUrl();
        if(lastUrl.matches("http://sh\\.bendibao\\.com/news/list_17_162_1\\.htm") && bool==true){
            List<String> listUrl=httpPage.getHtml().xpath("//p[@class=\"tag_nav\"]/a/@href").all();
            bool=false;
            for (String url:listUrl){
                if(url.matches("http://sh\\.bendibao\\.com/news/list_17_\\d*_\\d*\\.htm")){
                    CrawlerRequestRecord turnPageRequest = CrawlerRequestRecord.builder()
                            .itemPageRequest(crawlerRequestRecord)
                            .recordKey(url)
                            .httpUrl(url)
                            .releaseTime(System.currentTimeMillis())
                            .build();

                    parsedLinks.add(turnPageRequest);
                }
            }
        }else if(lastUrl.matches("http://sh\\.bendibao\\.com/news/list_17_\\d*_\\d*\\.htm")){
            int curPage = Integer.parseInt(lastUrl.substring(lastUrl.lastIndexOf("_") + 1).split("\\.")[0]);
            String nextPageUrl = lastUrl.substring(0,lastUrl.lastIndexOf("_") + 1) + (curPage + 1) + ".htm";
            CrawlerRequestRecord turnPageRequest = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .recordKey(nextPageUrl)
                    .httpUrl(nextPageUrl)
                    .releaseTime(System.currentTimeMillis())
                    .build();

            parsedLinks.add(turnPageRequest);


            List<Selectable> itemNodes = httpPage.getHtml().xpath("//ul[@id=\"listNewsTimeLy\"]/li").nodes();
            for (Selectable itemNode : itemNodes) {
                String itemUrl = itemNode.xpath("./div[@class=\"info\"]/h3/a/@href").get();
                if (StringUtils.isBlank(itemUrl)){
                    continue;
                }
                String pubTime = itemNode.xpath("./div[@class=\"info\"]/p[@class=\"from\"]/text()").get();
                try {
                    long releaseTime = DateUtils.parseDate(pubTime, "yyyy-MM-dd HH:mm").getTime();

                    CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                            .itemPageRequest(crawlerRequestRecord)
                            .recordKey(itemUrl)
                            .httpUrl(itemUrl)
                            .needParsed(false)
                            .releaseTime(releaseTime)
                            .resultLabelTag(article)
                            .build();
                    parsedLinks.add(itemRecord);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }

        return parsedLinks;
    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRecord, HttpPage page) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        CrawlerResultTags crawlerResultTags = crawlerRecord.tagsCreator().resultTags();
        if (crawlerResultTags.hasDataType(article)) {
            crawlerDataList.add(washArticle(crawlerRecord, page));

        }

        if (crawlerResultTags.hasDataType(interaction)) {
            crawlerDataList.add(washInteraction(crawlerRecord, page));
        }

        return crawlerDataList;
    }

    public CrawlerData washArticle(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        Map<String,String> article = new HashMap<>();
        try {
            List<String> texts = httpPage.getHtml().xpath("//div[@class=\"content\"]/p/text()").all();

            String releaseTime = httpPage.getHtml().xpath("//span[@class=\"time\"]/text()").get();//发布时间：2020-09-30
            if(releaseTime!=null){
                releaseTime=releaseTime.substring(releaseTime.indexOf("：")+1);
            }

            StringBuffer conents = new StringBuffer();
            for (String text : texts) {
                conents.append(text).append(" ");
            }

            String author = "";
            Matcher mtAuthor = Pattern.compile("decodeURIComponent\\(\"\\S*\"\\)").matcher(httpPage.getRawText());
            while (mtAuthor.find()){
                try {
                    author = URLDecoder.decode(mtAuthor.group(0).split("\"")[1],"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    log.error("parse author error : unknown URL Code " + mtAuthor.group(0));
                }
            }

            String itemUrl = httpPage.getRequest().getUrl();
            String articleKey = itemUrl.split("/")[itemUrl.split("/").length-2];

            CrawlerData crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .url(itemUrl)
                    .releaseTime(DateUtils.parseDate(releaseTime,"yyyy-MM-dd HH:mm").getTime())
                    .addContentKV("content",conents.toString().trim())
                    .addContentKV("title",httpPage.getHtml().xpath("//div[@class=\"title daoyu\"]/h1/strong/text()").get())
                    .addContentKV("author",author)
                    .build();
            return crawlerData;
        } catch (ParseException e) {
            log.error(e.getMessage(),e);
        }
        return null;

    }

    public CrawlerData washInteraction(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {

        return null;
    }

    @Override
    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {

    }
}
